define(['jquery', 'bootstrap', 'backend', 'table', 'form','template'], function ($, undefined, Backend, Table, Form, Template) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pricereviewmanagent/pricing_review/index' + location.search,
                    add_url: 'pricereviewmanagent/pricing_review/add',
                    edit_url: 'pricereviewmanagent/pricing_review/edit',
                    del_url: 'pricereviewmanagent/pricing_review/del',
                    multi_url: 'pricereviewmanagent/pricing_review/multi',
                    import_url: 'pricereviewmanagent/pricing_review/import',
                    detail_url: 'pricereviewmanagent/pricing_review/detail',
                    table: 'project',
                }
            });

            var table = $("#table");
            var projectConfig = Config.projectConfig;
            var tenderTypeList = Config.tenderTypeList;
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                height:700,
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true,formatter: function(value, row, index) {
                            return {
                                disabled: !(Config.childrenAdminIds.indexOf(row.admin_id) > -1)
                            };
                        }},
                        {field: 'id', title: __('Id'),sortable:true},
                        {field: 'project_name', title: __('Project_name'), operate: 'LIKE', formatter:function (value, row, index) {
                            return "<a href='javascript:void(0);' style='color: #4397fd' class='btn-dialog' " +
                                        "data-url='pricereviewmanagent/pricing_review/detail/ids/"+row.id+"' data-title='项目详情' data-area=[\"100%\",\"100%\"] >" + row.project_name + "</a>";
                        }},
                        {field: 'project_address', title: __('Project_address'), operate: 'LIKE',formatter:function (value, row, index) {
                            return row.mergename+(row.project_address || '')
                        }},
                        
                        {field: 'submission_unit', title: __('Submission_unit')},
                        
                        {field: 'admin.nickname', title: __('Admin_id')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                        buttons: [{
                            name: 'edit',
                            icon: 'fa fa-pencil',
                            title: __('Edit'),
                            extend: 'data-toggle="tooltip" data-container="body"',
                            classname: 'btn btn-xs btn-success btn-editone',
                            visible: function (row) {
                                return Config.childrenAdminIds.indexOf(row.admin_id) > -1;
                            }
                        },{
                            name: 'del',
                            icon: 'fa fa-trash',
                            title: __('Del'),
                            extend: 'data-toggle="tooltip" data-container="body"',
                            classname: 'btn btn-xs btn-danger btn-delone',
                            visible: function (row) {
                                return Config.childrenAdminIds.indexOf(row.admin_id) > -1;
                            }
                        }], formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            $(document).on("click",'#btn-import-xml',function() {
                Fast.api.open($.fn.bootstrapTable.defaults.extend.import_url, "导入项目", {area:["100%","100%"]});
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'pricereviewmanagent/pricing_review/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'project_name', title: __('Project_name')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'pricereviewmanagent/pricing_review/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'pricereviewmanagent/pricing_review/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        import: function () {
            
            Controller.api.bindevent();
        },
        tabledetail    : {
            
            list1: function () {
                //操作日志
                var table1 = $("#operation_list");
                var bkcolor = '#fa9085';
                // 初始化表格
                table1.bootstrapTable({
                    url          : 'pricereviewmanagent/pricing_review_items/getListByProject?id='+Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    sortOrder    : 'asc',
                    toolbar      : "#toolbar_list",
                    height       : 600,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    pagination   : false,
                    fixedColumns: true,
                    // fixedRightNumber: 1,
                    fixedNumber: 4,
                    rowStyle: function (row, index) {
                        return {
                            css:{
                                display: row.pid == 0 ? "" : "none",
                                "background-color": row.max_project_itemid == 0 && row.min_project_itemid == 0 && row.max_project_itemid == 0 && row.avg_project_itemids == '' ? bkcolor : ""
                            }
                        }
                    },
                    responseHandler:function(res) {
                        $('#listcount').html(res.total > 0 ? '('+res.total+')' : '')
                        return res;
                    },
                    columns      : [
                        [
                            {checkbox: true},
                            {field: 'id', title: __('序号'), formatter:function (value,row,index,field) {
                                //row.level
                                return index+1
                            }},
                            {field: 'code', title: __('项目编码')},
                            {field: 'name', title: __('项目名称'), align:'left', cellStyle:function (value,row,index,field) {
                                    return {
                                        css: {
                                            "min-width": "200px",
                                            "white-space": "unset",
                                            "text-overflow": "ellipsis",
                                            "overflow": "hidden",
                                            "max-width":"250px",
                                            'cursor':"pointer",
                                            "background-color": row.max_project_itemid == 0 && row.min_project_itemid == 0 && row.max_project_itemid == 0 && row.avg_project_itemids == '' ? bkcolor : ""
                                        }
                                    };
                                },
                                 clickToSelect: false
                            },
                            
                            {field: 'description', title: __('项目特征描述'),cellStyle:function (value,row,index,field) {
                                    return {
                                        css: {
                                            "min-width": "200px",
                                            "white-space": "unset",
                                            "text-overflow": "ellipsis",
                                            "overflow": "hidden",
                                            "max-width":"250px",
                                            'cursor':"pointer",
                                            "background-color": row.max_project_itemid == 0 && row.min_project_itemid == 0 && row.max_project_itemid == 0 && row.avg_project_itemids == '' ? bkcolor : ""
                                        }
                                    };
                                },formatter:function (value,row,index,field) {
                                    var span=document.createElement('span');
                                    span.setAttribute('title',value);
                                    span.innerHTML = value;
                                    return span.outerHTML;
                                }
                            },
                            {field: 'unit', title: __('计量单位')},
                            {field: 'quantity', title: __('工程量'), formatter:function (value,row,index,field) {
                                return parseFloat(value) > 0 ? value : '-'
                            }},
                            {field: 'unit_price', title: __('综合单价(元)'), formatter:function (value,row,index,field) {
                                return parseFloat(value) > 0 ? value : '-'
                            }},
                            {field: 'maxprice', title: __('最高价(元)'), formatter:function (value,row,index,field) {
                                return parseFloat(value) > 0 ? "<a href='javascript:void(0);' style='color: #4397fd' class='btn-dialog' " +
                                "data-url='project_list/detail/ids/"+row.max_project_itemid+"' data-title='项目详情' data-area=[\"100%\",\"100%\"] >" + value + "</a>" : '-'
                            }},
                            {field: 'minprice', title: __('最低价(元)'), formatter:function (value,row,index,field) {
                                return parseFloat(value) > 0 ? "<a href='javascript:void(0);' style='color: #4397fd' class='btn-dialog' " +
                                "data-url='project_list/detail/ids/"+row.min_project_itemid+"' data-title='项目详情' data-area=[\"100%\",\"100%\"] >" + value + "</a>" : '-'
                            }},
                            {field: 'avgprice', title: __('平均价(元)'), formatter:function (value,row,index,field) {
                                if (parseFloat(value) <= 0) return '-';
        
                                // 编码参数
                                const encodedFilter = encodeURIComponent(row.avg_project_itemids);
                                const url = `project_list/index?ids=${encodedFilter}`;
                                const title = '【'+row.name+'('+row.code+')】项目列表';
                                
                                return `<a href='javascript:;' 
                                        class='btn-dialog' 
                                        data-url='${url}'
                                        data-title='${title}' 
                                        data-area='["100%","100%"]'
                                        style='color: #4397fd'>
                                        ${value}
                                    </a>`;
                            }},
                            // {field: 'operate', title: __('Operate'), table: table1, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                        ]
                    ]
                });
                
                Table.api.bindevent(table1);
            },
            
            basic:function (){

            }
        },
        detail: function () {
            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.length > 0) {
                    var control = 'pricereviewmanagent/pricing_review_items'
                    if (panel.attr("id") == 'list1') {
                        control = 'pricereviewmanagent/pricing_review_items'
                    }
                    // 关键修复1：解绑整个工具栏的点击事件
                    var toolbar = panel.find(".toolbar");
                    toolbar.off('click', '.btn-add,#btn-import-list'); 

                    // 关键修复2：彻底销毁表格及关联事件
                    var table = panel.find(".bootstrap-table");
                    if (table.length > 0) {
                        table.bootstrapTable('destroy');
                        table.data('bootstrap.table', null); // 清除缓存
                    }
                    // 初始化表格参数配置
                    Table.api.init({
                        extend: {
                            index_url: control+'/getListByProject' + location.search,
                            add_url: control+'/add?project_id='+Config.idinfo.id,
                            edit_url: control+'/edit',
                            del_url: control+'/del',
                            multi_url: control+'/multi',
                            import_url: control+'/import?project_id='+Config.idinfo.id,
                            detail_url: control+'/detail',
                            table: control,
                        }
                    });
                    
                    Controller.tabledetail[panel.attr("id")].call(this);
                    // $(this).on('click', function (e) {
                    //     $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    // });
                }
                //移除绑定的事件
                // $(this).unbind('shown.bs.tab');
            });
            $(document).on("click",'#btn-import-list',function() {
                Fast.api.open("pricereviewmanagent/pricing_review_items/import?project_id="+Config.idinfo.id, "导入清单", {area:["100%","100%"]});
            });
            $(document).on("click",'#btn-import-set',function() {
                Fast.api.open("pricereviewmanagent/pricing_review_items/importset?project_id="+Config.idinfo.id, "匹配设置", {area:["60%","50%"]});
            });
            $(document).on('click','#edits',function () {
                var id=$('#ids').val();
                Fast.api.open("pricereviewmanagent/pricing_review/edit?ids="+id, "项目编辑",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["95%","95%"],
                    callback:function(value){
                        location.reload();
                    },
                });

            })
            
            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
            Controller.api.bindevent();
        },
        
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                
                let originalData = []; // 用于存储原始数据
                let batchtimes = 0;
                let curtimes = 0;
                let lastrow = 0;
                $("#c-file").change(function () {
                    var file = $(this).val();
                    if (file) {
                        var that = this
                        that.layerIndex =layer.load(0,{ shade: 0.3 });
                        $.ajax({
                            url: "pricereviewmanagent/pricing_review/import_preview",
                            data: {file: file},
                            type: "post",
                            complete: function(){
                                layer.close(that.layerIndex);
                            },
                            success: function (res) {
                                if (res.code == 1) {
                                    originalData = res.data.data;
                                    batchtimes = res.data.batchtimes;
                                    // 调用模板渲染（方案1：直接渲染）
                                    // 结构化数据处理
                                    const renderData = {
                                        project_info: res.data.project_data || {},
                                        project_assess: res.data.project_assess || [],
                                        project_rencaiji: res.data.project_rencaiji || [],
                                        items: res.data.data || []
                                    };
                                    // 带错误捕获的模板渲染
                                    try {
                                        const html = Template('projecttpl', renderData);
                                        $('#wechat').empty().html(html);
                                        $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
                                        Form.api.bindevent($("form[role=form]"));
                                    } catch (e) {
                                        console.error('模板渲染错误:', e);
                                        Toastr.error('数据解析失败');
                                    }
                                } else {
                                    layer.msg(res.msg);
                                    return false;
                                }
                            }
                        });
                    }
                });
                var submit = function(form, success, error, submit) {
                    if (form.size() === 0) {
                        Toastr.error("表单未初始化完成,无法提交");
                        return false;
                    }
                    if (typeof submit === 'function') {
                        if (false === submit.call(form, success, error)) {
                            return false;
                        }
                    }
                    var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                    type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                    var url = form.attr("action");
                    url = url ? url : location.href;
                    // 调整 serialize 方法以收集修改过的数据
                    var file = form.find("input[name=file]");
                    // 构建最终的提交数据
                    var params = {curtimes};
                    // 修复当存在多选项元素时提交的 BUG
                    var multipleList = $("[name$='[]']", form);
                    if (multipleList.size() > 0) {
                        var postFields = form.serializeArray().map(function (obj) {
                            return obj.name;
                        });
                        $.each(multipleList, function (i, j) {
                            if (postFields.indexOf($(this).prop("name")) < 0) {
                                params[$(this).prop("name")] = '';
                            }
                        });
                    }
                    params = form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : '')
                    // 调用 Ajax 请求方法
                    // 返回一个新的Promise对象
                    return new Promise(function(resolve, reject) {
                        Fast.api.ajax({
                            type: type,
                            url: url,
                            data: params,
                            dataType: 'json',
                            complete: function (xhr) {
                                var token = xhr.getResponseHeader('__token__');
                                if (token) {
                                    $("input[name='__token__']").val(token);
                                }
                            }
                        }, function (data, ret) {
                            $('.form-group', form).removeClass('has-feedback has-success has-error');
                            if (data && typeof data === 'object') {
                                // 刷新客户端 token
                                if (typeof data.token !== 'undefined') {
                                    $("input[name='__token__']").val(data.token);
                                }
                                // 调用客户端事件
                                if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
                                    data.callback.call(form, data);
                                }
                            }
                            if (typeof success === 'function') {
                                if (false === success.call(form, data, ret)) {
                                    return false;
                                }
                            }
                            resolve(ret); // 解析Promise
                        }, function (data, ret) {
                            if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
                                $("input[name='__token__']").val(data.token);
                            }
                            if (typeof error === 'function') {
                                if (false === error.call(form, data, ret)) {
                                    return false;
                                }
                            }
                            reject(ret); // 拒绝Promise
                        });
                        return true;
                    });
                }
                $('#import-submit').click(function () {
                    var that = this,
                    form = $('#import-form'),
                    submitBtn = $(".layer-footer [type=submit]", form);
                    submitBtn.addClass("disabled");
                    async function submitForm(i) {
                        curtimes = i;
                        try {
                            const rets = await submit(form, function(data, ret){
                                if (ret.code == 1) {
                                    
                                }
                                if ((i + 1) === batchtimes) {
                                    submitBtn.removeClass("disabled");
                                    // 提示及关闭当前窗口
                                    var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
                                    parent.Toastr.success(msg);
                                    parent.$(".btn-refresh").trigger("click");
                                    var index = parent.Layer.getFrameIndex(window.name);
                                    parent.Layer.close(index);
                                }
                            }, function(data, ret){
                                if ((i + 1) === batchtimes) {
                                    submitBtn.removeClass("disabled");
                                }
                            });
                            // 如果需要根据`ret`做进一步处理
                            // console.log('Submit result:', rets);
                        } catch (error) {
                            // 处理错误情况
                            console.error('Error submitting form:', error);
                        }
                    }
                    
                    (async function processNext() {
                        for (let i = 0; i < batchtimes; i++) {
                            await submitForm(i); // 等待当前提交完成
                        }
                    })();
                    
                    return false
                })
            }
        }
    };
    return Controller;
});
